/*
 * @(#)SimpleXDSParser.java
 * Date 2014-01-18
 * Version 1.0
 * Author Jim Horner
 * Copyright (c)2012
 */


package us.hornerscorners.lamppost.registry.service;


import javax.enterprise.context.ApplicationScoped;

import oasis.names.tc.ebxml_regrep.xsd.lcm._3.SubmitObjectsRequest;

import oasis.names.tc.ebxml_regrep.xsd.rim._3.AdhocQueryType;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.ExternalIdentifierType;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.RegistryPackageType;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.SlotType1;

import org.apache.commons.lang3.ArrayUtils;

import us.hornerscorners.lamppost.registry.constant.Metadata;
import us.hornerscorners.lamppost.registry.constant.QuerySlotName;

import us.hornerscorners.lamppost.registry.utils.XDSUtils;


/**
 * Class description
 *
 *
 * @version        v1.0, 2014-01-18
 * @author         Jim Horner
 */
@ApplicationScoped
public class SimpleXDSParser {

    /** Field description */
    private final QuerySlotName[] pidQuerySlots;

    /**
     * Constructs ...
     *
     */
    public SimpleXDSParser() {

        super();

        this.pidQuerySlots = new QuerySlotName[] { QuerySlotName.PatientId,
                QuerySlotName.XDSDocumentEntryPatientId, QuerySlotName.XDSFolderPatientId,
                QuerySlotName.XDSSubmissionSetPatientId };
    }

    /**
     * Method description
     *
     *
     * @param query
     *
     * @return
     */
    public String parsePatientCX(AdhocQueryType query) {

        String result = null;

        for (SlotType1 slot : query.getSlot()) {

            QuerySlotName querySlot = QuerySlotName.toQuerySlotName(slot.getName());

            if (ArrayUtils.contains(this.pidQuerySlots, querySlot)) {

                result = XDSUtils.parseFirstValue(slot);
                break;
            }
        }

        return result;
    }

    /**
     * Method description
     *
     *
     * @param request
     *
     * @return
     */
    public String parsePatientCX(SubmitObjectsRequest request) {
        
        String result = null;

        RegistryPackageType regpack = XDSUtils.findSubmissionSet(request);

        if (regpack != null) {

            for (ExternalIdentifierType idtype : regpack.getExternalIdentifier()) {

                Metadata schemeType =
                    Metadata.toMetadata(idtype.getIdentificationScheme());

                if (Metadata.SubmissionSetPatientId.equals(schemeType)) {

                    result = idtype.getValue();

                    break;
                }
            }
        }

        return result;
    }

    /**
     * Method description
     *
     *
     * @param request
     *
     * @return
     */
    public String parseSubmissionSetId(SubmitObjectsRequest request) {

        String result = null;

        RegistryPackageType regpack = XDSUtils.findSubmissionSet(request);

        if (regpack != null) {

            result = regpack.getId();
        }

        return result;
    }
}
